const padNumber = number => {
  const value = typeof number === "number" ? number : parseInt(number, 10);
  if (Number.isNaN(value)) {
    return "00";
  }
  return value < 10 ? `0${value}` : `${value}`;
};

const callCloud = options => {
  const app = getApp && typeof getApp === "function" ? getApp() : null;
  if (app && typeof app.callCloudFunction === "function") {
    return app.callCloudFunction(options);
  }
  const { loadingTitle, ...rest } = options;
  const title =
    typeof loadingTitle === "string" && loadingTitle.trim()
      ? loadingTitle.trim()
      : "加载中...";
  wx.showLoading({ title, mask: true });
  const originalComplete = rest.complete;
  rest.complete = (...args) => {
    wx.hideLoading();
    if (typeof originalComplete === "function") {
      originalComplete(...args);
    }
  };
  return wx.cloud.callFunction(rest);
};

Page({
  data: {
    activities: [],
    loading: true,
    loadingMore: false,
    hasMore: true,
    page: 1,
    errorMessage: ""
  },

  onLoad() {
    this.activityImageCache = {};
    this.fetchActivities({ reset: true });
  },

  onPullDownRefresh() {
    this.fetchActivities({
      reset: true,
      done: () => wx.stopPullDownRefresh()
    });
  },

  onReachBottom() {
    if (this.data.loading || this.data.loadingMore || !this.data.hasMore) {
      return;
    }
    this.fetchActivities({ reset: false });
  },

  handleSearchTap() {
    wx.navigateTo({
      url: "/pages/search/search",
      fail: () => {
        wx.showToast({
          title: "搜索功能即将上线",
          icon: "none"
        });
      }
    });
  },

  handleAddActivityTap() {
    const app = typeof getApp === "function" ? getApp() : null;
    if (app && typeof app.ensureUserProfileForAction === "function") {
      const allowed = app.ensureUserProfileForAction("发起活动前请先完善个人信息");
      if (!allowed) {
        return;
      }
    }
    wx.navigateTo({
      url: "/pages/addActivity/addActivity",
      fail: () => {
        wx.showToast({
          title: "暂未开放添加活动",
          icon: "none"
        });
      }
    });
  },

  handleActivityTap(event) {
    const dataset =
      event && event.currentTarget ? event.currentTarget.dataset : null;
    const activityId = dataset ? dataset.activityId : "";

    if (!activityId) return;

    wx.navigateTo({
      url: `/pages/activity-detail/activity-detail?activityID=${activityId}`
    });
  },

  fetchActivities({ reset, done } = {}) {
    const nextPage = reset ? 1 : this.data.page + 1;

    if (reset) {
      this.setData({
        loading: true,
        loadingMore: false,
        errorMessage: "",
        hasMore: true
      });
    } else {
      this.setData({
        loadingMore: true,
        errorMessage: ""
      });
    }

    callCloud({
      name: "queryOngoingActivities",
      data: {
        tableNumber: nextPage
      },
      loadingTitle: "加载中...",
      success: res => {
        const activities = this.normalizeActivities(res);
        this.resolveActivityImages(activities)
          .then(resolved => {
            this.applyActivityListUpdate(resolved, nextPage, reset);
          })
          .catch(error => {
            console.error("resolveActivityImages failed", error);
            this.applyActivityListUpdate(activities, nextPage, reset);
          });
      },
      fail: err => {
        console.error("queryOngoingActivities failed", err);
        this.setData({
          errorMessage: "活动加载失败，请稍后重试",
          loading: false,
          loadingMore: false
        });
      },
      complete: () => {
        if (typeof done === "function") {
          done();
        }
      }
    });
  },

  applyActivityListUpdate(list, nextPage, reset) {
    const mergedActivities = reset ? list : this.data.activities.concat(list);

    this.setData({
      activities: mergedActivities,
      page: nextPage,
      hasMore: list.length > 0,
      loading: false,
      loadingMore: false
    });
  },

  resolveActivityImages(activities) {
    if (!Array.isArray(activities) || activities.length === 0) {
      return Promise.resolve([]);
    }

    const cache = this.activityImageCache || (this.activityImageCache = {});
    const toFetch = [];

    activities.forEach(item => {
      const image = item && item.activityImage;
      if (
        typeof image === "string" &&
        image.startsWith("cloud://") &&
        !cache[image]
      ) {
        toFetch.push(image);
      }
    });

    if (toFetch.length === 0) {
      return Promise.resolve(
        activities.map(activity => this.applyCachedImage(activity))
      );
    }

    const uniqueFileIDs = Array.from(new Set(toFetch));

    return wx.cloud
      .getTempFileURL({
        fileList: uniqueFileIDs
      })
      .then(res => {
        const fileList = (res && res.fileList) || [];
        fileList.forEach(file => {
          if (file.status === 0 && file.tempFileURL) {
            cache[file.fileID] = file.tempFileURL;
          }
        });
        return activities.map(activity => this.applyCachedImage(activity));
      })
      .catch(err => {
        console.error("getTempFileURL failed", err);
        // 失败时返回原始 activities，避免中断流程
        return activities;
      });
  },

  applyCachedImage(activity) {
    if (!activity) return activity;
    const cache = this.activityImageCache || {};
    const image = activity.activityImage;
    if (typeof image === "string" && cache[image]) {
      return Object.assign({}, activity, {
        activityImage: cache[image]
      });
    }
    return activity;
  },

  normalizeActivities(response) {
    const payload =
      (response && response.result) ? response.result : (response || {});
    const activities = Array.isArray(payload.activities)
      ? payload.activities
      : [];

    return activities.map(activity => {
      const safeActivity = activity || {};
      return {
        activityID: safeActivity.activityID || "",
        activityName: safeActivity.activityName || "未命名活动",
        activityImage: safeActivity.activityImage || "",
        activityTime: Array.isArray(safeActivity.activityTime)
          ? safeActivity.activityTime
          : [],
        activityLocation: safeActivity.activityLocation || "地点待定",
        activityTimeText: this.buildTimeText(safeActivity.activityTime)
      };
    });
  },

  buildTimeText(activityTime) {
    if (!Array.isArray(activityTime) || activityTime.length === 0) {
      return "时间待定";
    }

    const parts = activityTime
      .map(group => this.formatGroupTime(group))
      .filter(text => text);

    return parts.length > 0 ? parts.join(" / ") : "时间待定";
  },

  formatGroupTime(group) {
    if (!group) return "";

    const start = this.formatDateTime(group.startTime);
    const end = this.formatDateTime(group.endTime);

    if (start && end) return `${start} ~ ${end}`;
    if (start || end) return start || end;
    return "";
  },

  formatDateTime(value) {
    if (!value) return "";

    const date = new Date(value);
    if (Number.isNaN(date.getTime())) {
      return typeof value === "string" ? value : "";
    }

    const year = date.getFullYear();
    const month = padNumber(date.getMonth() + 1);
    const day = padNumber(date.getDate());
    const hours = padNumber(date.getHours());
    const minutes = padNumber(date.getMinutes());

    return `${year}年${month}月${day}日 ${hours}:${minutes}`;
  }
});
